package com.disktalk.web;

import com.disktalk.api.EKPAuth;
import com.disktalk.util.DesUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;

@Controller
@RequestMapping("/user")
public class UserController {

  private final static String DES = "DES";
  private final static String key = "kxde!@#$%";//
  private final static String value = "cx";//


  /**
   * 用户登录
   *
   * @param userName
   * @param password
   * @param request
   */
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public String login(@RequestParam(value = "userName", required = false) String userName,
                      @RequestParam(value = "password", required = false) String password,
                      HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
    System.out.println("userName:" + userName + "");
    if (userName != null && password != null) {
      boolean login = EKPAuth.login(userName, password);
      if (login) {
        String userAndPwd = userName + value + password;
        String tokenByUserName = DesUtil.getTokenByUserName(userAndPwd);
        addcookie("token", tokenByUserName, 1800, response);
//          Cookie cookieToken = new Cookie("token", tokenByUserName);
//          cookieToken.setMaxAge(60 * 30);
//          cookieToken.setPath("/");
//          response.addCookie(cookieToken);
        System.out.println("添加cookie");
        return "welcome";
      }
    }
//      else {
//      String userToken = decrypt(token, key);
//      String[] uNameAndPwd = userToken.split(value);
//      String userName1 = uNameAndPwd[0];
//      String pwd = uNameAndPwd[1];
//      String name1 = MD5Util.string2MD5(userName1);
//      String pwd1 = MD5Util.string2MD5(pwd);
//      if (password.equals(pwd1) && userName.equals(name1)) {
//        //changeUrl(request, response, userName1);
//      } else {
//        boolean login = EKPAuth.login(userName, password);
//        if (login) {
//          return "redirect:/file/list";
//        }
//      }
//    }
    return "login";
  }

  @RequestMapping(value = "/login", method = RequestMethod.GET)
  public String login( @RequestParam(value = "token", required = false) String token, HttpServletResponse response) {
    if(token!=null&&(!"".equals(token))){
      String userAndPwd = new DesUtil().decrypt(token, key);
      String[] uNameAndPwd = userAndPwd.split(value);
      String userName = uNameAndPwd[0];
      String password = uNameAndPwd[1];
      if(EKPAuth.login(userName, password)){
        addcookie("token", token, 1800, response);
        return "welcome";
      }
    }

    return "login";
  }
  /**
   * 重定向地址
   *
   * @param request
   * @param response
   * @param userName1
   * @throws Exception
   *//*
  private static void changeUrl(HttpServletRequest request, HttpServletResponse response, String userName1) throws Exception {
    String localhost = "http://localhost:8080/disktalk/file/list?userName=" + userName1;
    System.err.println("===========chenxiao==============");
    response.sendRedirect(localhost);
  }*/

/**
 * 加密解密算法 执行一次加密，两次解密
 *
 * @param inStr
 * @return
 */
  /**
   * @param inStr
   * @return
   */
  public static String convertMD5(String inStr) {

    char[] a = inStr.toCharArray();
    for (int i = 0; i < a.length; i++) {
      a[i] = (char) (a[i] ^ 't');
    }
    String s = new String(a);
    return s;

  }


  /**
   * Description 根据键值进行解密
   *
   * @param data
   * @param key  加密键byte数组
   * @return
   * @throws IOException
   * @throws Exception
   */
  public static String decrypt(String data, String key) throws Exception {
    if (data == null) {
      return null;
    }
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] buf = decoder.decodeBuffer(data);
    byte[] bt = decrypt(buf, key.getBytes());
    return new String(bt);
  }

  /**
   * Description 根据键值进行解密
   *
   * @param data
   * @param key  加密键byte数组
   * @return
   * @throws Exception
   */
  private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
    // 生成一个可信任的随机数源
    SecureRandom sr = new SecureRandom();

    // 从原始密钥数据创建DESKeySpec对象
    DESKeySpec dks = new DESKeySpec(key);

    // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    System.out.println();
    SecretKey securekey = keyFactory.generateSecret(dks);

    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance(DES);

    // 用密钥初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

    return cipher.doFinal(data);
  }
  private void addcookie (String key,String value,int time,HttpServletResponse response){
    Cookie cookieToken = new Cookie(key, value);
    cookieToken.setMaxAge(time);
    cookieToken.setPath("/");
    response.addCookie(cookieToken);
  }

}
